from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Planting_Plan_schema
from controller import Planting_Plan_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Planting_Plan", response_model=Planting_Plan_schema.Planting_plan, tags=["Planting_Plan"])
async def create_Planting_Plan(Planting_Plan: Planting_Plan_schema.Planting_plan, db: Session = Depends(get_db)):
    return Planting_Plan_controller.create_Planting_Plan(db, Planting_Plan)


@router.get("/Planting_Plan/{ID}", response_model=Planting_Plan_schema.Planting_plan, tags=["Planting_Plan"])
async def get_Planting_Plan(ID: int, db: Session = Depends(get_db)):
    db_Planting_Plan = Planting_Plan_controller.get_Planting_Plan(db, ID)
    if db_Planting_Plan is None:
        raise HTTPException(status_code=404, detail="Planting_Plan not found")
    return db_Planting_Plan


@router.get("/Planting_Plan", response_model=List[Planting_Plan_schema.Planting_plan], tags=["Planting_Plan"])
async def get_all_Planting_Plan(db: Session = Depends(get_db)):
    all_db_Planting_Plan = Planting_Plan_controller.get_all_Planting_Plan(db)
    if all_db_Planting_Plan is None:
        raise HTTPException(status_code=404, detail="0 Planting_Plan found, empty table")
    return all_db_Planting_Plan


@router.put("/Planting_Plan/{ID}", tags=["Planting_Plan"])
async def update_Planting_Plan(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Planting_Plan = Planting_Plan_controller.update_Planting_Plan(db, ID, field_name, field_value)
        if db_Planting_Plan is None:
            raise HTTPException(status_code=404, detail="Planting_Plan not found")
        return db_Planting_Plan
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Planting_Plan/{ID}", tags=["Planting_Plan"])
async def delete_Planting_Plan(ID: int, db: Session = Depends(get_db)):
    is_deleted = Planting_Plan_controller.delete_Planting_Plan(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
